/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       lock.h
 * Author:     karooolek
 * Created on: 2009-02-27
 *
 **********************************************************************************************************************/

#ifndef LOCK_H_
#define LOCK_H_

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <pthread.h>
#endif

namespace mGameEngine
{

/**
 * Lock for synchronizing threads.
 * Used to create critical sections of code - a code
 * that can be executed by only one thread at a time.
 */
class Lock
{
private:
#ifdef WIN32
    /**
     * Mutex.
     */
    CRITICAL_SECTION _mutex;
#else
    /**
     * Mutex
     */
    pthread_mutex_t _mutex;
#endif

public:
    /**
     * Create lock with initial state.
     * @param locked lock initial state.
     */
    Lock(bool locked = false);

    /**
     * Destroy lock.
     */
    ~Lock();

    /**
     * Close lock.
     * If lock is already closed program will wait until it opens.
     */
    void lock();

    /**
     * Try to close lock.
     * If lock is already closed program will not wait.
     * @return true if locking succeded, false otherwise.
     */
    bool tryLock();

    /**
     * Open lock.
     */
    void unlock();
};

}

#endif // LOCK_H_
